<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CProjectApplicationForm">
          <a-row>
					  <!-- 加入的横线 -->
					  <a-col :span="24">
						  <a-divider >项目基础信息</a-divider >
					  </a-col>
            <a-col :span="12" v-if="formData.additionalId">
              <a-form-item label="项目增项" v-bind="validateInfos.additionalId" id="CProjectApplicationForm-additionalId" name="additionalId">
                 <j-dict-select-tag showSearch="true"   disabled="true" v-model:value="formData.additionalId"  dictCode="c_additional_request,title,id" placeholder="请选择项目增项"  allow-clear />
              </a-form-item>
            </a-col>

						<a-col :span="12">
							<a-form-item label="项目编号" v-bind="validateInfos.projectNumber" id="CProjectApplicationForm-projectNumber" name="projectNumber">
								<a-input style="width: 70%" v-model:value="formData.projectNumber"  placeholder="请输入项目编号"  allow-clear ></a-input>
								<a-button v-if="formData.id==='' " type="primary" style="margin-left: 8px;" @click="generateContractNumber">生成合同编号</a-button>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="项目名称" v-bind="validateInfos.projectName" id="CProjectApplicationForm-projectName" name="projectName">
								<a-input v-model:value="formData.projectName" placeholder="请输入项目名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						
						<a-col :span="12">
							<a-form-item label="关联库" v-bind="validateInfos.libraryId" id="CProjectApplicationForm-libraryId" name="libraryId">
								 <j-dict-select-tag
                  showSearch="true"
                  v-model:value="formData.libraryId"  dictCode="c_library,name,id" placeholder="请选择关联库"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="发包单位" v-bind="validateInfos.contractingUnit" id="CProjectApplicationForm-contractingUnit" name="contractingUnit">
								 <j-dict-select-tag showSearch="true"   v-model:value="formData.contractingUnit" dictCode="c_contracting_unit,name,id" placeholder="请选择发包单位"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="总包主体" v-bind="validateInfos.companyInfoId" id="CProjectApplicationForm-companyInfoId" name="companyInfoId">
								 <j-dict-select-tag showSearch="true"   v-model:value="formData.companyInfoId" dictCode="c_company_info,company_name,id" placeholder="请选择总包主体"  allow-clear />
							</a-form-item>
						</a-col>

            <a-col :span="12">
              <a-form-item label="项目类型" v-bind="validateInfos.projectType" id="CProjectApplicationForm-projectType" name="projectType">
                <j-dict-select-tag showSearch="true"   v-model:value="formData.projectType" dictCode="project_type" placeholder="请选择项目来源"  allow-clear />
              </a-form-item>
            </a-col>
						<a-col :span="12">
							<a-form-item label="项目来源" v-bind="validateInfos.source" id="CProjectApplicationForm-source" name="source">
								 <j-dict-select-tag showSearch="true"   v-model:value="formData.source" dictCode="application_source" placeholder="请选择项目来源"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="管理费" v-bind="validateInfos.manageFee" id="CProjectApplicationForm-manageFee" name="manageFee">
                <a-input-number v-model:value="formData.manageFee" placeholder="请输入管理费" style="width: 100%" />
              </a-form-item>
            </a-col>

<!--            <a-col :span="12">
              <a-form-item label="立项时间" v-bind="validateInfos.paymentDate" id="CProjectApplicationForm-establishmentTime" name="establishmentTime">
                <a-date-picker
                  placeholder="请选择立项时间"
                  v-model:value="formData.establishmentTime"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>-->
						
						<a-col :span="12" >
							<a-form-item label="项目图纸" v-bind="validateInfos.projectDrawings" id="CProjectApplicationForm-projectDrawings" name="projectDrawings">
								<j-upload v-model:value="formData.projectDrawings"  dragger="true"   :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }" ></j-upload>
							</a-form-item>
						</a-col>
						<a-col :span="12" >
							<a-form-item label="附件" v-bind="validateInfos.attachmentUrl" id="CProjectApplicationForm-attachmentUrl" name="attachmentUrl">
								<j-upload v-model:value="formData.attachmentUrl" dragger="true"  :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }" ></j-upload>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="项目描述" v-bind="validateInfos.projectDescription" id="CProjectApplicationForm-projectDescription" name="projectDescription">
								<a-textarea v-model:value="formData.projectDescription" :rows="4" placeholder="请输入项目描述" />
							</a-form-item>
						</a-col>
			     </a-row >
				
						
				
							
					<a-row >
							<!-- 加入的横线 -->
							<a-col :span="24">
								<a-divider >合同</a-divider >
							</a-col>
							<a-col :span="12">
								<a-form-item label="关联合同" v-bind="validateInfos.contractId" id="CProjectApplicationForm-contractId" name="contractId">
									<j-select-multiple  type="list_multi" v-model:value="formData.contractId" disabled ="true"
									 dictCode="c_contract,contract_no,id" placeholder="请选择关联合同" @change="contractOnChange"  :triggerChange="true"/>
								</a-form-item>
							</a-col>
							<a-col :span="24">
								<a-card title="" :bordered="false">
								      <a-descriptions v-for="(item, index) in contractList" :key="index" size="small" :column="4">
								        <a-descriptions-item label="合同编号">{{ item.contractNo }}</a-descriptions-item>
								        <a-descriptions-item label="合同金额">{{ item.contractAmount }}</a-descriptions-item>
								        <a-descriptions-item label="税率">{{ item.taxRate }}%</a-descriptions-item>
								        <a-descriptions-item label="含税价">{{ item.taxIncludingPrice }}</a-descriptions-item>
								      </a-descriptions>
								    </a-card>
							</a-col>
							
							<!-- <a-col :span="12">
							<a-form-item label="合同价" v-bind="validateInfos.contractPrice" id="CProjectApplicationForm-contractPrice" name="contractPrice">
									<a-input-number v-model:value="formData.contractPrice" placeholder="请输入合同价" style="width: 100%" />
								</a-form-item>
							</a-col>
							<a-col :span="12">
			
								<a-form-item label="合同价是否含税价" v-bind="validateInfos.taxIncluded" id="CDemoForm-taxIncluded" name="taxIncluded">
									<j-switch v-model:value="formData.taxIncluded"  ></j-switch>
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item label="税率" v-bind="validateInfos.taxRate" id="CProjectApplicationForm-taxRate" name="taxRate">
									<a-input-number v-model:value="formData.taxRate" placeholder="请输入税率" style="width: 40%" />%
								</a-form-item>
							</a-col> -->
						</a-row>
						<!-- 加入的横线 -->
				<a-row >
						<!-- <a-col :span="24">
						    <a-divider >相关资料</a-divider >
						</a-col>
						<a-col :span="12">
							<a-form-item label="项目合同" v-bind="validateInfos.projectContract" id="CProjectApplicationForm-projectContract" name="projectContract">
								<j-upload v-model:value="formData.projectContract"  dragger="true"   ></j-upload>
								<a-button type="primary" @click="viewAttachment(formData.projectContract)">查看</a-button>
								<span style="color: red;">上传合同，项目状态立项</span>
							</a-form-item>
						</a-col> -->

          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';

  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate,getContractById } from '../CProjectApplication.api';
  import { Form } from 'ant-design-vue';
  import JSelectMultiple from '/@/components/Form/src/jeecg/components/JSelectMultiple.vue';
  import JSwitch from '/@/components/Form/src/jeecg/components/JSwitch.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import {encryptByBase64} from "@/utils/cipher";
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    projectNumber: '',   
    projectName: '',   
    projectDescription: '',   
    address: '',   
    projectStatus: '立项',
    manageFee: '',
    contractingUnit: '',   
    contractPrice: undefined,
    taxRate: undefined,
    source: '立项',   
    projectContract: '',   
    projectDrawings: '',
    libraryId: '',
    duration: undefined,
    startDate: '',   
    endDate: '',   
    actualStartTime: '',   
    actualCompletionTime: '',   
    attachmentUrl: '',   
    fileRecordId: '',
	  taxIncluded:'',
	  contractId:'',
    mergeProjectId: '',
    companyInfoId:'',
    additionalId:'',
    establishmentTime:''
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  let contractList = ref([])
  
  //表单验证
  const validatorRules = reactive({
    //projectNumber: [{ required: true, message: '请输入项目编号!'},],
	//contractingUnit: [{ required: true, message: '请输入发包单位!'},],
	//source: [{ required: true, message: '请输入项目来源！'},],
    projectName: [{ required: true, message: '请输入项目名称!'},],
    //projectType: [{ required: true, message: '请输入项目类型!'},],
   // contractPrice: [{ required: true, message: '请输入合同价!'},],
   // taxRate: [{ required: true, message: '请输入税率!'},],
   // startDate: [{ required: true, message: '请输入预计开始日期!'},],
    //endDate: [{ required: true, message: '请输入预计结束日期!'},],
	//companyInfo: [{ required: true, message: '请输入发包主体'},],
	//taxIncluded: [{ required: true, message: '请输入合同价是否含税价'},],
	
  });
  


  
  
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });



  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });
  
  function calculateDuration(){
	 const startDate = formData.startDate;
	 const endDate = formData.endDate;
	  if (startDate && endDate) {
	    const start = new Date(startDate);
	    const end = new Date(endDate);
	    const diffTime = Math.abs(end - start);
	    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
	    formData.duration = diffDays;
	} else {
	    formData.duration = null; // 清空结果
	}
	 
  }
  
	function generateContractNumber() {
       formData.projectNumber = generateContractNumbermethod()
    }
	
	function generateContractNumbermethod() {
	   // 示例：生成一个简单的合同编号
	   const date = new Date().toISOString().slice(0, 10).replace(/-/g, '');
	   const randomString = Math.random().toString().substring(2, 6);
	   return `YC-${date}-${randomString}`;
	   
	}
	
  /**
   * 新增
   */
  function add(record) {
    edit(record);
  }


  /**
   * 编辑
   */
  function edit(record) {

    if(record === undefined || record === null){
      record = {}
    }

	if(record.projectNumber ===undefined || record.projectNumber ===null){
	  record['projectNumber']=generateContractNumbermethod()
	 }

    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
	  contractInfo(record.contractId)
      //赋值
      Object.assign(formData, tmpData);
    });
	
	
  }
  
  async function contractInfo(contractId){
	  contractList.value=[]
	  if(contractId){
		  const contractIds = contractId.split(",")
		  for(var i=0;i<contractIds.length;i++){
		  		  const param = {'id':contractIds[i]}
            debugger
           try {
             const result = await getContractById(param)
             if(result){
               contractList.value.push({
                 "contractNo":result.contractNo,
                 "contractAmount":result.contractAmount,
                 "taxRate":result.taxRate,
                 "taxIncludingPrice":result.taxIncludingPrice,
                 "contractFile":result.contractFile,
               })
             }
           }catch (e) {
             createMessage.error("关联合同未找到"+contractIds[i]);
           }
		  }
	  }
	  
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
	  const data = await validate();
    } catch ({ errorFields }) {
		
      if (errorFields) {
		  for(var i=0;i<errorFields.length;i++){
			  const firstField = errorFields[i];
			  if(formData.projectContract != "" || firstField.name.includes("projectNumber") ||  firstField.name.includes("projectName")){
				  if (firstField) {
					 
				    formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
					return Promise.reject(errorFields);
				  }
			  }
		  }
      }
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }
  
  async function changeContract(value){
	
	// alert(result)
  }
  
   function contractOnChange(value){
	  
	  contractInfo(value)
  }
  
  onMounted(() => {
	 // alert(formData.contractId)
  })
  

  defineExpose({
    add,
    edit,
    submitForm,
	generateContractNumber,
	calculateDuration,
	generateContractNumbermethod,
	changeContract,
	contractList,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
